package org.example.laboratorymanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.laboratorymanagement.mapper.LaborMapper;
import org.example.laboratorymanagement.pojo.Labor;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.service.LaborService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class LaborServiceImpl  implements LaborService {

    @Autowired
    private LaborMapper laborMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public PageBean pagelabors(Integer page, Integer pageSize, String name, String local, String e) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        List<Labor> teachers = laborMapper.listLabors(name, local,e);
        Page<Labor> p = (Page<Labor>) teachers;

        // 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }

    @Override
    public void delete(List<Integer> ids) {
        laborMapper.delete(ids);
    }

    @Override
    public void update(Labor labor) {
        laborMapper.update(labor);
    }

    @Override
    public Labor selectById(Integer id) {
        return laborMapper.selectById(id);
    }

    @Override
    public void add(Labor labor) {
        laborMapper.insert(labor);
    }

    @Override
    public List<Labor> selectAll() {
        return laborMapper.selectAll();
    }

    @Override
    public void insertBatch(List<Labor> labors) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            LaborMapper laborMapper = sqlSession.getMapper(LaborMapper.class);
            labors.stream().forEach(labor -> laborMapper.insert(labor));
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

    }
}
